/*
 * @(#)HttpClientRepository.java $version 2011. 11. 28.
 *
 * Copyright 2011 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.mywep.myalimi.common.http;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import com.mywep.myalimi.model.Rss;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;


/**
 * @author 한지웅
 */
public class HttpClientRepository {
	private static final Logger LOG = LoggerFactory.getLogger(HttpClientRepository.class);
	protected HttpClientTemplate httpClientTemplate;

	public String getXMLElement(String url, String elementName) {
		try {
			String xml = httpClientTemplate.execute(url);
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(new StringReader(xml));
			Element root = document.getRootElement();
			if (root.getChild("error") != null) {
				return null;
			}
			return root.getChild(elementName).getText();
		} catch (JDOMException e) {
			return null;
		} catch (IOException e) {
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Rss> getRSSElements(String url) {
		try {
			String rssStr = httpClientTemplate.execute(url);

			SyndFeedInput feedInput = new SyndFeedInput();
			SyndFeed feed = feedInput.build(new InputSource(new ByteArrayInputStream(rssStr.getBytes())));
			
			List<Rss> rssList = new ArrayList<Rss>();
			for (Object objectEntry : feed.getEntries()) {
				SyndEntry syndEntry = (SyndEntry)objectEntry;
				Rss rss = new Rss();
				rss.setTitle(syndEntry.getTitle());
				rss.setAuth(syndEntry.getAuthor());
				rss.setCategroyList(syndEntry.getCategories());
				rss.setDate(syndEntry.getPublishedDate());
				rss.setDescription(syndEntry.getDescription().getValue());
				rss.setUrl(syndEntry.getUri());
				
				rssList.add(rss);
			}

			return rssList;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			return new ArrayList<Rss>();
		}

	}
	
}
